<?php
/**
 * Author: Nguyen Hoai Tan (nguoiao007@gmail.com)
 * 
 * @category   default 
 * @copyright  Copyright (c) 2009 visualidea.org
 * @license    http://license.visualidea.org
 * @version    v 1.0 2009-04-15
 * 
 */
require_once 'Shared/Models/Ads.php';
require_once 'Shared/Models/AdsCategory.php';
require_once 'Shared/Models/Portal.php'; 
require_once 'Vi/Auth.php';
require_once 'Vi/Acl.php';
class ads_AdminController extends Vi_Controller_Action_Admin 
{
    
    public function managerAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('see_ads', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $this->view->headTitle(Vi_Language::translate('Ads Manager'));
        $this->view->menu = array('ads', 'adsmanager');
        
        
        $config = Vi_Registry::getConfig();
        $numRowPerPage = Vi_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page",1);
        $displayNum = $this->_getParam('displayNum', false);
        
        $objAds     = new Models_Ads();
        $objAdsCat  = new Models_AdsCategory();
        
        /**
         * Update sorting
         */
        $data = $this->_getParam('data', array());
        foreach ($data as $id=>$value) {
            $value = intval($value);
            if (1 > $value) {
                continue;
            }
            $objAds->update(array('sorting' => $value), array('ads_id=?' => $id));
            $this->session->adsMessage = array(
                                       'success' => true,
                                       'message' => Vi_Language::translate("Edit sort numbers successfully")
                                   );
        }
       
        /**
         * Get number of items per page
         */
        if (false === $displayNum) {
            $displayNum = $this->session->contentDisplayNum;
        } else {
            $this->session->contentDisplayNum = $displayNum;
        }
        if (null != $displayNum) {
            $numRowPerPage = $displayNum;
        }
        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->contentCondition;
        } else {
            $this->session->contentCondition = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }
        
        /**
         * Get all categories
         */
        $allAdsCats = $objAdsCat->getAll(array('sorting ASC'))->toArray();
        
        /**
         * Get all Ads
         */
		$userId = Vi_Registry::getLoggedInUserId();
		if(1 == $userId) {
			$allAds = $objAds->getAllAdsWithCategory($condition, array('sorting ASC', 'ads_id DESC'),
                                                   $numRowPerPage,
                                                   ($currentPage - 1) * $numRowPerPage
                                                  );
		} else {
        	$allAds = $objAds->getAllAdsWithCategoryAndUserId($condition, array('sorting ASC', 'ads_id DESC'),
                                                   $numRowPerPage,
                                                   ($currentPage - 1) * $numRowPerPage, $userId
                                                  );
		}
        /**
         * Count all Ads
         */
//		$portalId = $objAds->getPortalId();
		$count = $objAds->countAllAds($condition);

		/**
         * Set values for tempalte
         */
        $this->setPagination($numRowPerPage, $currentPage, $count);
        $this->view->allAds = $allAds;
        $this->view->allAdsCats = $allAdsCats;
        $this->view->adsMessage = $this->session->adsMessage;
        $this->session->adsMessage = null;
        $this->view->condition = $condition;
        $this->view->displayNum = $numRowPerPage;
        $this->view->fullPermisison = $this->checkPermission('see_ads');
    }
    
    public function newAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('new_ads', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $data = $this->_getParam('data', false);
        
        /**
         * Get all Ads Categories
         */
        $objAdsCat = new Models_AdsCategory();
        $objPortal = new Models_Portal();
        $allAdsCats = $objAdsCat->getAll(array('sorting ASC'))->toArray();
        $allPortals = $objPortal->getAll()->toArray();
        
        $errors = array();
        if (false !== $data) {
        
            /**
             * Insert new Ads
             */
            $objAds = new Models_Ads();
            $data['image'] = $this->_getImagePath($data['image']);
            if(null == trim($data['custom_code'])) {
            	$data['custom_code'] = null;
            }
            if (true == $this->checkPermission('new_ads', null, '*')) {
                $newAds = array(
                                'name'               => $data['name'],
                                'portal_id'          => $data['portal_id'],
                                'ads_category_id'    => $data['ads_category_id'],
                                'sorting'            => $data['sorting'],
                                'click'              => 0,
                				'max_click'          => $data['max_click'], 
                                'enabled'            => $data['enabled'],
                				'important'          => $data['important'],
                				'click_url'          => $data['click_url'],
                				'custom_code'        => $data['custom_code'],
                				'image'              => $data['image'],
                				'width'              => $data['width'],
                				'height'             => $data['height'],
                				'description'        => $data['description'],
                            );
            } else {
//                $defaultAdsCat = current($allAdsCats);
//                $newAds = array(
//                                'scontent_category_id' => $defaultAdsCat['scontent_category_id'],
//                                'enabled'              => 0,
//                                'publish_up_date'      => null,
//                                'publish_down_date'    => null,
//                                'sorting'              => 1,
//                                'enable_comment'      => 0,
//                                'created_date'         => time()
//                            );
            }
            
            $objAds->insert($newAds);
            $this->_redirect('ads/admin/manager');
            
            /**
             * Sorting
             */
            if (null == $newAds['sorting']) {
                unset($newAds['sorting']);
            }
            /**
             * Check URL for all language contents
             */
            $errors = true;
            
            if (true === $errors) {
                try {
                    /**
                     * Increase all current sortings
                     */
                    if (1 > $newAds['sorting']) {
                        $newAds['sorting'] = 1;
                    }
                    $objAds->increaseSorting($newAds['sorting'], 1);
                    
                    $id = $objAds->insert($newAds);
                    $this->_redirect('ads/admin/manager');
                } catch (Exception $e) {
                    $errors = array('main' => Vi_Language::translate('Can not insert into database now'));
                }
            }
        } else {
            $data = array('sorting' => 1);
        }
        /**
         * Prepare for template
         */
        $this->view->allAdsCats = $allAdsCats;
        $this->view->allPortals = $allPortals;
        $this->view->errors = $errors;
        $this->view->data = $data;
        $this->view->headTitle(Vi_Language::translate('New Ads'));
        $this->view->menu = array('ads', 'adsnew');
        $this->view->fullPermisison = $this->checkPermission('new_ads', null, '*'); 
    }
    
	public function editAction()
    {
     	if (false == $this->checkPermission('edit_ads', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
    	$id = $this->_getParam('id', false);
     	if (false == $id) {
            $this->_redirect('ads/admin/manager');
        }
		$data = $this->_getParam('data',false);
		if(false != $data) {
			$objAds = new Models_Ads();
			$data['image'] = $this->_getImagePath($data['image']); 
			$objAds->update($data, array('ads_id=?' => $id));
            $this->session->adsMessage = array(
                                       'success' => true,
                                       'message' => Vi_Language::translate("Edit ads successfully")
                                   );
			$this->_redirect('ads/admin/manager');                                   
		} else {
			$objAds = new Models_Ads();
			$data = $objAds->find($id)->toArray();
			$data = current($data);
			if (false == $data) {
				$this->session->adsMessage = array(
                                               'success' => false,
                                               'message' => Vi_Language::translate("Ads doesn't exist.")
                                           );
				$this->_redirect('ads/admin/manager');
			}
		}
		$objPortal = new Models_Portal();
		$objAdsCat = new Models_AdsCategory();
		$allPortals = $objPortal->getAll()->toArray();
		$allAdsCats = $objAdsCat->getAll()->toArray();
		
		$this->view->data = $data;
		$this->view->allPortals = $allPortals;
		$this->view->allAdsCats = $allAdsCats;
		$this->view->adsMessage = $this->session->adsMessage;
		$this->session->adsMessage = null;
		$this->view->headTitle(Vi_Language::translate('Edit Ads'));
		$this->view->menu = array('ads');
		$this->view->fullPermisison = $this->checkPermission('edit_ads', null, '*');
    }

    public function enableAdsAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('edit_ads', null, '*')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        $id = $this->_getParam('id', false);
        
        if (false == $id) {
            $this->_redirect('ads/admin/manager');
        }
        
        $ids = explode('_', trim($id, '_'));
        
        $objAds = new Models_Ads();
        try {
            foreach ($ids as $id) {
               $objAds->update(array('enabled' => 1), array('ads_id=?' => $id));
            }
            $this->session->adsMessage = array(
                                               'success' => true,
                                               'message' => Vi_Language::translate('Enable ads successfully')
                                           );
        } catch (Exception $e) {
            $this->session->adsMessage = array(
                                               'success' => false,
                                               'message' => Vi_Language::translate('Can NOT enable this ads. Please try again')
                                           );
        }
        $this->_redirect('ads/admin/manager');
    }

    
    
    public function disableAdsAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('edit_ads', null, '*')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        $id = $this->_getParam('id', false);
        
        if (false == $id) {
            $this->_redirect('ads/admin/manager');
        }
        
        $ids = explode('_', trim($id, '_'));
        
        $objAds = new Models_Ads();
        try {
            foreach ($ids as $id) {
               $objAds->update(array('enabled' => 0), array('ads_id=?' => $id));
            }
            $this->session->adsMessage = array(
                                               'success' => true,
                                               'message' => Vi_Language::translate('Disable ads successfully')
                                           );
        } catch (Exception $e) {
            $this->session->adsMessage = array(
                                               'success' => false,
                                               'message' => Vi_Language::translate('Can NOT disable this ads. Please try again')
                                           );
        }
        $this->_redirect('ads/admin/manager');
    }

   
    
    public function deleteAdsAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('delete_ads')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        $id = $this->_getParam('id', false);
        
        if (false == $id) {
            $this->_redirect('ads/admin/manager');
        }
        
        $ids = explode('_', trim($id, '_'));
        
        $objAds = new Models_Ads();
        try {
            foreach ($ids as $id) {
               $objAds->delete(array('ads_id=?' => $id));
            }
            $this->session->adsMessage = array(
                                               'success' => true,
                                               'message' => Vi_Language::translate('Delete ads successfully')
                                           );
        } catch (Exception $e) {
            $this->session->adsMessage = array(
                                               'success' => false,
                                               'message' => Vi_Language::translate('Can NOT delete this ads. Please try again')
                                           );
        }
        $this->_redirect('ads/admin/manager');
    }
    
	private function _getImagePath($path)
    {
        return substr($path, strlen(Vi_Registry::getBaseUrl()));
    }
}